package org.goodsl.mdd.validator;

import java.net.IDN;
import java.util.regex.Matcher;

import org.goodsl.mdd.Seg;
import org.goodsl.mdd.SingleValidResult;
import org.goodsl.mdd.Validator;

/**
 * Created with IntelliJ IDEA.
 * User: Simon Xiao
 * Date: 12-11-14
 * Time: 上午9:36
 * To change this template use File | Settings | File Templates.
 */
public class EmailValidator extends Validator<Seg> {

    private static String ATOM = "[a-z0-9!#$%&'*+/=?^_`{|}~-]";
   	private static String DOMAIN = "(" + ATOM + "+(\\." + ATOM + "+)*";
   	private static String IP_DOMAIN = "\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\]";

   	private java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(
   			"^" + ATOM + "+(\\." + ATOM + "+)*@"
   					+ DOMAIN
   					+ "|"
   					+ IP_DOMAIN
   					+ ")$",
   			java.util.regex.Pattern.CASE_INSENSITIVE
   	);

    public EmailValidator(String message) {
        super(message);

    }

    @Override
    public SingleValidResult<Seg> verify(Seg variable) {
        String valueStr = variable.getValue().toString();
        String asciiString = IDN.toASCII(valueStr);
        Matcher m = pattern.matcher( asciiString );
        if(m.matches())
            return new SingleValidResult<Seg>(true, "", variable, this);
        else
            return new SingleValidResult<Seg>(false, getMessage(), variable, this);

    }

}
